package com.example.framework.base;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import com.example.framework.R;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

/**
 * When Crash Caused By The UncaughtException Occur, This Class Will Catch The Exception,
 * Save The Crash Log On External Storage Card, And Send The Log To Server.
 * 
 * @author renxin.sun
 *
 */
public class CrashHandler implements UncaughtExceptionHandler
{
	public static final String TAG = "CrashHandler";

	/**
	 * Declare UncaughtExceptionHandler object.
	 */
	private Thread.UncaughtExceptionHandler mDefaultHandler;
	
	/**
	 * Declare CrashHandler object.
	 */
	private static CrashHandler instance;

	/**
	 * Declare Context object.
	 */
	private Context mContext;
	
	private float mExceptionLogSize;
	
	private final static long MB = 1048576;
	
	/**
	 * Used to store information of storage device and exception.
	 */
	private Map<String, String> infos = new HashMap<String, String>();

	/**
	 * Used to format DateTime which will be used for a part of Log's filename.
	 */
	private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",Locale.getDefault());

	/**
	 * Guarantee only one instance.
	 */
	private CrashHandler()
	{
	}

	/**
	 * Get the one instance.
	 * @return Instance of CrashHandler.
	 */
	public static CrashHandler getInstance()
	{
		if (instance == null)
			instance = new CrashHandler();
		return instance;
	}

	/**
	 * Initialize CrashHandler object. It will be used in CrashApplication.java.
	 */
	public void init(Context context)
	{
		mContext = context;
		
		mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		
		Thread.setDefaultUncaughtExceptionHandler(this);
	}

	@Override
	public void uncaughtException(Thread thread, Throwable ex)
	{
		if (!handleException(ex) && mDefaultHandler != null)
		{
			mDefaultHandler.uncaughtException(thread, ex);
		}
		else
		{
			try
			{
				Thread.sleep(3000);
			}
			catch (InterruptedException e)
			{
				Log.e(TAG, "error : ", e);
			}
			/**
			 * exit the application.(killProcess can lead to restart application!)
			 */
//			android.os.Process.killProcess(android.os.Process.myPid());
			CustomApplication.getInstance().exit(1);
		}
	}

	/**
	 * Self-defining error information's handling,generate the file,and send file to servers.
	 * @param ex
	 * @return if has handled return true, or false.
	 */
	private boolean handleException(Throwable ex)
	{
		if (ex == null)
		{
			return false;
		}
		
		collectDeviceInfo(mContext);

		new Thread()
		{
			@Override
			public void run()
			{
				Looper.prepare();
				Toast.makeText(mContext, R.string.sorrytoexit, Toast.LENGTH_SHORT).show();
				Looper.loop();
			}
		}.start();
		
		//
		updateLogSize();
		// This method include save and send file.
		saveCatchInfoToFile(ex);
		
		return true;
	}

	private void updateLogSize()
	{
		mExceptionLogSize = PreferenceManager.getDefaultSharedPreferences(mContext).getFloat(CustomApplication.CACHE_SIZE, CustomApplication.EXCEPTION_DEFAULT_CACHE);

		if (isSDCardEnable())
		{
			String extStorageDirectory = Environment.getExternalStorageDirectory().toString();

			String dirPath = extStorageDirectory + CustomApplication.CACHE_DIR + "CrashLog";

			File dirFile = new File(dirPath);

			if (!dirFile.exists())
			{
				dirFile.mkdirs();
			}
			
			File[] files = dirFile.listFiles();

			long dirSize = 0;

			for (File file : files)
			{

				dirSize += file.length();
			}

			if (dirSize > mExceptionLogSize * MB)
			{
				clearCache();
			}
		}
	}

	/**
	 * Collect device information and parameters.
	 * 
	 * @param ctx
	 */
	public void collectDeviceInfo(Context ctx)
	{
		try
		{
			PackageManager pm = ctx.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
			if (pi != null)
			{
				String versionName = pi.versionName == null ? "null" : pi.versionName;
				String versionCode = pi.versionCode + "";
				infos.put("versionName", versionName);
				infos.put("versionCode", versionCode);
			}
		}
		catch (NameNotFoundException e)
		{
			Log.e(TAG, "an error occured when collect package info", e);
		}
		Field[] fields = Build.class.getDeclaredFields();
		for (Field field : fields)
		{
			try
			{
				field.setAccessible(true);
				infos.put(field.getName(), field.get(null).toString());
				Log.d(TAG, field.getName() + " : " + field.get(null));
			}
			catch (Exception e)
			{
				Log.e(TAG, "an error occured when collect crash info", e);
			}
		}
	}

	/**
	 * Save the error information to file.
	 * 
	 * @param ex
	 * @return the file name.
	 */
	private String saveCatchInfoToFile(Throwable ex)
	{

		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String> entry : infos.entrySet())
		{
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key + "=" + value + "\n");
		}

		Writer writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		ex.printStackTrace(printWriter);
		Throwable cause = ex.getCause();
		while (cause != null)
		{
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}
		printWriter.close();
		String result = writer.toString();
		sb.append(result);
		try
		{
			long timestamp = System.currentTimeMillis();
			String time = formatter.format(new Date());
			String fileName = "crash-" + time + "-" + timestamp + ".log";
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
			{
				String path = Environment.getExternalStorageDirectory().getPath() + CustomApplication.CACHE_DIR + "CrashLog";
				File dir = new File(path);
				if (!dir.exists())
				{
					dir.mkdirs();
				}
				FileOutputStream fos = new FileOutputStream(path + "/" + fileName);
				fos.write(sb.toString().getBytes());
				// send to servers.
				sendCrashLogToServers(path + fileName);
				fos.close();
			}
			return fileName;
		}
		catch (Exception e)
		{
			Log.e(TAG, "an error occured while writing file...", e);
		}
		return null;
	}

	/**
	 * send the crash log file to servers.
	 * @param fileName
	 */
	private void sendCrashLogToServers(String fileName)
	{
		if (!new File(fileName).exists())
		{
			Toast.makeText(mContext, R.string.inexistence_log, Toast.LENGTH_SHORT).show();
			return;
		}
		FileInputStream fis = null;
		BufferedReader reader = null;
		String s = null;
		try
		{
			fis = new FileInputStream(fileName);
			reader = new BufferedReader(new InputStreamReader(fis, "GBK"));
			while (true)
			{
				s = reader.readLine();
				if (s == null)
					break;
				// execute send to servers operation.
				// add at this.now is null.
			}
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				reader.close();
				fis.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	
	private void clearCache()
	{

		if (isSDCardEnable())
		{
			String extStorageDirectory = Environment.getExternalStorageDirectory().toString();

			String dirPath = extStorageDirectory + CustomApplication.CACHE_DIR + "CrashLog";

			File dir = new File(dirPath);

			File[] files = dir.listFiles();

			if (files == null || files.length == 0)
			{
				return;
			}

			for (File file : files)
			{
				file.delete();
			}

			Log.d(CustomApplication.IMAGECACHE_TAG, "cleared cache:" + dirPath);
		}
	}
	
	public static boolean isSDCardEnable()
	{

		return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
	}

}
